//
//  SLBackListViewController.m
//  StarLight
//
//  Created by Duke.wu on 16/6/7.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLBackListViewController.h"
#import "UUMessageCell.h"
#import "UUMessage.h"
#import "UUMessageFrame.h"
#import "UUInputFunctionView.h"
#import "MJRefresh.h"
#import "SLBackMsgViewModel.h"


@interface SLBackListViewController ()<UUInputFunctionViewDelegate,UUMessageCellDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) SLBackMsgViewModel *chatModel;

@property (strong, nonatomic) MJRefreshNormalHeader *head;

@property (nonatomic, strong) UITableView *chatTableView;

@property (nonatomic, strong) UUInputFunctionView *IFView;


@end

@implementation SLBackListViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setupUI];
  [self addRefreshViews];
  [self loadBaseViewsAndData];
}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  self.title = @"反馈信息";
  [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
  [super viewDidAppear:animated];
  
  //add notification
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tableViewScrollToBottom) name:UIKeyboardDidShowNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
  [super viewWillDisappear:animated];
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)setupUI{
  
  self.view.backgroundColor = [UIColor defeutBackgroudColor];
  
  [self.view addSubview:self.chatTableView];
  [self.chatTableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.centerX.equalTo(self.view);
    make.top.equalTo(self.view);
    make.bottom.equalTo(self.view).offset(-40);
  }];
  
  @weakify(self)
  
  self.chatTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    @strongify(self)
    [self.chatModel first];
  }];
}

- (void)addRefreshViews
{
  
  
  @weakify(self)
  
  [[RACObserve(self.chatModel, backMsgList) filter:^BOOL(NSMutableArray *value) {
    return  value.count > 0;
  }] subscribeNext:^(id x) {
    @strongify(self)
    [self reload];
  }];
  

  

}

- (void)reload{
  
  @weakify(self)
  NSInteger pageNum = 1;
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:pageNum inSection:0];
  
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    @strongify(self)
    [self.chatTableView reloadData];
//    [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  });
  [self.chatTableView.header endRefreshing];
}

- (void)loadBaseViewsAndData
{
  self.chatModel = [[SLBackMsgViewModel alloc]init];
  
  self.IFView = [[UUInputFunctionView alloc]initWithSuperVC:self];
  self.IFView.delegate = self;
  [self.view addSubview:self.IFView];
  
  [self.chatTableView reloadData];
  [self tableViewScrollToBottom];
}

-(void)keyboardChange:(NSNotification *)notification
{
  NSDictionary *userInfo = [notification userInfo];
  NSTimeInterval animationDuration;
  UIViewAnimationCurve animationCurve;
  CGRect keyboardEndFrame;
  
  [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
  [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
  [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
  
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:animationDuration];
  [UIView setAnimationCurve:animationCurve];
  
  //adjust ChatTableView's height
  if (notification.name == UIKeyboardWillShowNotification) {
    [self.chatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
      make.bottom.equalTo(self.view).offset(-(keyboardEndFrame.size.height+40));
    }];
  }else{
    [self.chatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
      make.bottom.equalTo(self.view).offset(-40);
    }];
  }
  
  [self.view layoutIfNeeded];
  
  //adjust UUInputFunctionView's originPoint
  CGRect newFrame = self.IFView.frame;
  newFrame.origin.y = keyboardEndFrame.origin.y - newFrame.size.height;
  self.IFView.frame = newFrame;
  
  [UIView commitAnimations];
  
}

//tableView Scroll to bottom
- (void)tableViewScrollToBottom
{
  if (self.chatModel.backMsgList.count==0)
    return;
  
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatModel.backMsgList.count-1 inSection:0];
  [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


#pragma mark - InputFunctionViewDelegate
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message
{

  SLBckMsgModel *model = [SLBckMsgModel new];
  model.content = message;
  model.type = @"1";
  funcView.TextViewInput.text = @"";
  [funcView changeSendBtnWithPhoto:YES];
  [self dealTheFunctionData:model];
}

- (void)dealTheFunctionData:(SLBckMsgModel *)model
{
  [self.chatModel addSpecifiedItem:model];
  [self.chatTableView reloadData];
  [self tableViewScrollToBottom];
}

#pragma mark - tableView delegate & datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  return self.chatModel.backMsgList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  UUMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
  if (cell == nil) {
    cell = [[UUMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
    cell.delegate = self;
  }
  [cell setMessageFrame:self.chatModel.backMsgList[indexPath.row]];
  return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  return [self.chatModel.backMsgList[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
  [self.view endEditing:YES];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
  if (!self.reach.isReachable) {
    return [[NSAttributedString alloc] initWithString:@"无网络连接, 请连接网络后刷新" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }
  return [[NSAttributedString alloc] initWithString:@"暂无反馈信息" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
}


- (UITableView *)chatTableView{
  if(!_chatTableView){
    _chatTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _chatTableView.delegate = self;
    _chatTableView.emptyDataSetSource = self;
    _chatTableView.dataSource = self;
    _chatTableView.tableFooterView = [UIView new];
    [_chatTableView registerClass:[UUMessageCell class] forCellReuseIdentifier:@"CellID"];
  }
  return _chatTableView;
}

- (SLBackMsgViewModel *)chatModel{
  if(!_chatModel){
    _chatModel = [SLBackMsgViewModel new];
  }
  return _chatModel;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
